from serverproxy import *
from mainwindow import *
import tkMessageBox

class Controller(object):
    """
    Handles the communication between the UI and the server.
    """
    
    def __init__(self):
        self.serverProxy = ServerProxy("http://localhost", 0xBEEF)
        self.window = MainWindow(self)
        self.project = None
        
    def run(self):
        self.window.mainloop()
        
    def updateWindowTitle(self):
        if self.project == None:
            self.window.title("DBMS")
        else:
            self.window.title(self.project.name + " - DBMS")
        
        
        
        
    """ ------------ MainWindow Event Handlers ------------ """
        
        
        

    def onCreateProject(self):
        name = askstring('Nouveau projet', 'Veuillez entrer le nom du nouveau projet')
        if name == None:
            return
        
        project = self.serverProxy.createProject(name)
        if project == None:
            tkMessageBox.showerror("Erreur", "Impossible de creer le projet")
            return
        
        self.project = project
        self.updateWindowTitle()
        
    def onOpenProject(self):
        name = askstring('Nouveau projet', 'Veuillez entrer le nom du projet a ouvrir')
        if name == None:
            return
        
        project = self.serverProxy.getProjectByName(name)
        if project == None:
            tkMessageBox.showerror("Erreur", "Impossible d'ouvrir le projet")
            return 
        
        self.project = project
        self.updateWindowTitle()
        
    def onShowProject(self):
        if self.project == None:
            tkMessageBox.showerror("Erreur", "Aucun projet n'est charge")
            return 
        
        if self.window.frame.__class__ == ProjectFrame:
            return
        
        self.window.destroyFrame()
        frame = ProjectFrame(self.window, self)
        frame.setName(self.project.name)
        frame.setSummary(self.project.summary)
        frame.setMandate(self.project.mandate)
        self.window.setFrame(frame)
        
        
        
        
    """ ------------ ProjectFrame Event Handlers ------------ """
    
    
    
    
    def onSaveProjectChanges(self, name, summary, mandate):
        self.serverProxy.updateProject(self.project.id, name, summary, mandate)
        self.project.name = name
        self.project.summary = summary
        self.project.mandate = mandate
    

if __name__ == '__main__':
    controller = Controller()
    controller.run()